package org.ohos.rajawali3d.examples.examples;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.graphics.Surface;
import ohos.agp.render.opengl.EGLConfig;
import ohos.agp.render.opengl.GLES1X;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.multimodalinput.event.TouchEvent;
import ohos.opengl.GLSurfaceProvider;
import ohos.utils.net.Uri;
import org.ohos.rajawali3d.ResourceTable;
import org.ohos.rajawali3d.examples.views.GitHubLogoView;
import org.rajawali3d.renderer.ISurfaceRenderer;
import org.rajawali3d.renderer.Renderer;
import org.rajawali3d.view.IDisplay;
import org.rajawali3d.view.SurfaceView;

public abstract class AExampleFragment extends AbilitySlice implements IDisplay, Component.ClickedListener {
    protected SurfaceView mRenderSurface;
    protected ISurfaceRenderer mRenderer;
    protected ProgressBar mProgressBarLoader;
    protected DirectionalLayout mLayout2;
    protected StackLayout mLayout;
    protected GitHubLogoView mImageViewExampleLink;
    private String mExampleUrl;
    public static final String BUNDLE_EXAMPLE_URL = "BUNDLE_EXAMPLE_URL";

    public Component onCreateView(LayoutScatter inflater, ComponentContainer container, Intent savedInstanceState) {
        return null;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_relative_layout_loader_container);
        mLayout = (StackLayout) findComponentById(ResourceTable.Id_relative_layout_loader_container);
        mLayout2 = (DirectionalLayout) findComponentById(ResourceTable.Id_rajwali_surface);
        mProgressBarLoader = (ProgressBar) findComponentById(ResourceTable.Id_progress_bar_loader);
        mRenderSurface = new org.rajawali3d.view.SurfaceView(this);
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(0xFFFF0000));
        mRenderSurface.setBackground(shapeElement);
        mRenderSurface.setTransparent(true);
        ComponentContainer.LayoutConfig lc = new ComponentContainer.LayoutConfig();
        lc.width = ComponentContainer.LayoutConfig.MATCH_PARENT;
        lc.height = ComponentContainer.LayoutConfig.MATCH_PARENT;
        mLayout2.addComponent(mRenderSurface, lc);
        onCreateView(LayoutScatter.getInstance(getContext()), mLayout, intent);
        mRenderer = createRenderer();
        onBeforeApplyRenderer();
        applyRenderer();
        mImageViewExampleLink = (GitHubLogoView) mLayout.findComponentById(ResourceTable.Id_image_view_example_link);
        mImageViewExampleLink.setClickedListener(this);
        if (intent == null || !intent.hasParameter(BUNDLE_EXAMPLE_URL)) {
            throw new IllegalArgumentException(getClass().getSimpleName()
                    + " requires " + BUNDLE_EXAMPLE_URL + " argument at runtime!");
        }

        mExampleUrl = intent.getStringParam(BUNDLE_EXAMPLE_URL);
    }

    protected void onBeforeApplyRenderer() {
        mRenderSurface.setFrameRate(60);
        mRenderSurface.setRenderMode(GLSurfaceProvider.RENDERMODE_CONTINUOUSLY);
    }

    protected void applyRenderer() {
        mRenderSurface.setEGLContextClientVersion(3);
        mRenderSurface.setSurfaceRenderer(mRenderer);
    }

    @Override
    public void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_image_view_example_link) {
            if (mImageViewExampleLink == null)
                throw new IllegalStateException("Example link is null!");

            try {
                final Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")// 跳转的目的设备，空字符串表示本机
                        .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                        .withUri(Uri.parse(mExampleUrl))
                        .withAction("android.intent.action.VIEW")
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            } catch (Exception ignored) {
                ignored.printStackTrace();
            }
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
        mRenderSurface.onResume();
        mImageViewExampleLink.startDrawing();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        mRenderSurface.onPause();
    }

    protected void hideLoader() {
        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                mProgressBarLoader.setVisibility(Component.HIDE);
            }
        });
    }

    protected void showLoader() {
        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                mProgressBarLoader.setVisibility(Component.VISIBLE);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        mRenderSurface.onComponentUnboundFromWindow(mRenderSurface);
    }

    public Surface getRenderSurface() {
        return mRenderSurface.getSurface();
    }

    protected static abstract class AExampleRenderer extends Renderer {

        final AExampleFragment exampleFragment;

        public AExampleRenderer(Context context, AExampleFragment fragment) {
            super(context);
            exampleFragment = fragment;
        }

        public AExampleFragment getExampleFragment() {
            return exampleFragment;
        }

        @Override
        public void onRenderSurfaceCreated(EGLConfig config, GLES1X gl, int width, int height) {
            super.onRenderSurfaceCreated(config, gl, width, height);
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {

        }

        @Override
        public void onTouchEvent(TouchEvent event) {
        }

        @Override
        protected void onRender(long elapsedRealtime, double deltaTime) {
            super.onRender(elapsedRealtime, deltaTime);
        }
    }
}
